<?php

namespace app\api\controller;

use app\api\model\User as UserModel;


/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $model = new UserModel;
        return $this->renderSuccess([
            'user_id' => $model->login($this->request->post()),
            'token' => $model->getToken()
        ]);
    }
    //YPP 小程序获取城市信息
    public function getcity(){
        $longitude = $_REQUEST['longitude'];
        $latitude = $_REQUEST['latitude'];
        $city = $this->getCityName($latitude,$longitude,'N7wPxnqsyR91sA8xOIF7wnwCxu7cddXy');
        $city = str_replace("市","",$city['result']['addressComponent']['city']);
        $result['city'] = $city;
        return $result;

    }

    function getCityName($lat,$lng,$ak)
    {
        $content = file_get_contents("http://api.map.baidu.com/geocoder?location=$lat,$lng&output=json&key=$ak");
        $json = json_decode($content,true);
        return $json;
    }
    //YPP 小程序授权获取手机号
    public function getphone()
    {
        /**
         * code 换取 session_key
         * ​这是一个 HTTPS 接口，开发者服务器使用登录凭证 code 获取 session_key 和 openid。
         * 其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全，session_key 不应该在网络上传输。
         */
        $code = $_REQUEST['code'];
        $appId = $_REQUEST['appid'];
        $appSecret = $_REQUEST['appSecret'];
        $iv = $_REQUEST['iv'];
        $encryptedData = $_REQUEST['encryptedData'];

        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $arr = ['appid' => $appId,'secret' => $appSecret,'grant_type' => 'authorization_code','js_code' => $code];
        $dataresult = $this->curl($url, $arr);
        $result = json_decode($dataresult, true);
        if (isset($result['errcode'])) {
            return false;
        }
        $sessionKey = $result['session_key'];
        $res = $this->decryptData($encryptedData, $iv,$sessionKey);
        if($res['phoneNumber'] != ''){
            $userInfo = $this->getUser();
            $model = new UserModel;
            $user = $model->where(array("user_id"=>$userInfo['user_id']))->find();
            file_put_contents('ypp0001.php', "<?php\r\nreturn " . var_export($user, true) . "?>", FILE_APPEND);
            $data['mobile'] = $res['phoneNumber'];
            $user->allowField(true)->save($data);
        }
        return $res;
    }
    // 小程序解密

    public function decryptData($encryptedData, $iv,$sessionKey)
    {

        $aesKey=base64_decode($sessionKey);
        $aesIV=base64_decode($iv);
        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result,true);
        return  $dataObj;
        // return self::$OK;
    }


    function curl($url, $data = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        return $this->renderSuccess(compact('userInfo'));
    }

}
